package com.nbsaas.boot.controller.scheduling;

import com.nbsaas.boot.jobs.HttpJob;
import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.rest.response.ResponseObject;
import com.nbsaas.boot.scheduling.api.apis.SchedulingTaskApi;
import com.nbsaas.boot.scheduling.api.domain.simple.SchedulingTaskSimple;
import com.nbsaas.boot.scheduling.data.entity.SchedulingTask;
import org.quartz.*;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class TaskController {

    @Resource
    private Scheduler scheduler;

    @Resource
    private SchedulingTaskApi scheduleTaskApi;

    @Resource
    private ApplicationContext applicationContext;

    @RequestMapping("/start")
    public ResponseObject<?> start() throws SchedulerException {
        if (scheduler.isStarted()) {
            scheduler.start();
        }
        return ResponseObject.success();
    }

    @RequestMapping("/pause")
    public ResponseObject<?> pause() throws SchedulerException {
        scheduler.pauseAll();
        return ResponseObject.success();
    }

    @RequestMapping("/resume")
    public ResponseObject<?> resume() throws SchedulerException {
        scheduler.resumeAll();
        return ResponseObject.success();
    }


    @RequestMapping("/loadTasks")
    public ResponseObject<?> loadTasks() throws SchedulerException {

        if (!scheduler.isStarted()) {
            scheduler.resumeAll();
        }

        List<SchedulingTaskSimple> tasks = scheduleTaskApi.listData(Filter.ge("id", 0L));
        if (tasks != null) {
            for (SchedulingTaskSimple task : tasks) {


                Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression()))
                        .withIdentity("trigger" + task.getId(), "group" + task.getId()).build();
                if (!scheduler.checkExists(trigger.getKey())) {

                    JobDetail jobDetail = JobBuilder.newJob(HttpJob.class)
                            .withIdentity("job" + task.getId(), "group" + task.getId())
                            .usingJobData("url", task.getUrl())
                            .usingJobData("id", task.getId()).build();
                    jobDetail.getJobDataMap().put("applicationContext", applicationContext);


                    scheduler.scheduleJob(jobDetail, trigger);
                }
            }
        }

        return ResponseObject.success();
    }
}
